package org.zachary.agent.application;

import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import org.zachary.agent.application.exception.UserAlreadyExists;
import org.zachary.agent.domain.aggregate_model.user.User;
import org.zachary.agent.domain.aggregate_model.user_credit.UserCredit;
import org.zachary.agent.domain.repository.UserCreditRepository;
import org.zachary.agent.domain.repository.UserRepository;
import org.zachary.agent.infrastructure.feign.NotifyCreditScoreManager;
import org.zachary.agent.infrastructure.repository.InitDimensionAndRankingTableMapper;
import org.zachary.agent.infrastructure.utils.HiloGenerator;
import org.zachary.commonmodule.entity.entity.CreditDTO;

import java.util.UUID;

@Service
public class UserRegistrationService {
    private final UserRepository userRepo;
    private final UserCreditRepository userCreditRepo;
    private final HiloGenerator hilo;
    private final InitDimensionAndRankingTableMapper mapper;
    private final NotifyCreditScoreManager notifyCreditScoreManager;
    public UserRegistrationService(UserRepository userRepo, UserCreditRepository userCreditRepo, HiloGenerator hilo, InitDimensionAndRankingTableMapper mapper, NotifyCreditScoreManager notifyCreditScoreManager) {
        this.userRepo = userRepo;
        this.userCreditRepo = userCreditRepo;
        this.hilo = hilo;
        this.mapper = mapper;
        this.notifyCreditScoreManager = notifyCreditScoreManager;
    }

    @Transactional
    public Integer register(String name, String password) throws Exception {
        if (userRepo.findByUsername(name)!=null) {
            return 500;
        }
        int id=hilo.generateId();
        User user = new User(id,UUID.randomUUID().toString(),name, password);
        user.register();
        userRepo.save(user);
        // 初始化基本信用分
        UserCredit uc=UserCredit.init(id);
        userCreditRepo.init(uc);
        notifyCreditScoreManager.addCredit(new CreditDTO(
                id,0
        ));
        return 200;
    }
}
